import clientPicker from "../customerComm/clientPicker.vue";
import browseList from "../customerComm/browseList.vue";
import followPopup from "../customerComm/followPopup.vue";
import customerLabel from "../customerComm/customerLabel.vue";
import recordData from "../customerComm/recordList.vue";
import { scrollMixin } from "../../../utils/mixin";
import { Dialog} from "vant";
import maintainPopup from "../customerComm/maintainPopup.vue";
import loadingC from "../../../components/loading.vue";
import Vue from 'vue';
// Vue.use(Cascader);
// import { Message } from "element-ui";
import { Steps,Step} from "element-ui";
Vue.use(Steps).use(Step)

export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      popup_title:"",
      isLoading:false,
      temporary:"",
      otherMemberList:[],
      has_owned:false,
      recover_day:null,
      customer_base:[],
      member_page:1,
      member_total_page:1,
      isLoadMoreMember:true,
      current_type:"",
      member_list:[],//员工列表
      staff_id:"",//员工id
      member_name:"",
      keywork:"",
      show_member:false,
      names:"",

      business_status:[],
      business_type:[],
      files_list:[],
      file_ids:[],//客户商机文件
      business_type_name:"",
      business_status_name:"",
      business_list:[],
      business_columns_status:[],
      business_columns_type:[],
      show_details_page:false,
      show_business_status:false,
      show_business_type:false,
      business_form:{
        status_id:"",
        type_id:"",
        staff:"",
        name:"",
        details:""
      },

      form: {
        content: "",
        files: []
      },
      agentData: {
        // 企业微信config接口配置
        agent_secret: "",
        agentid: "",
        corpid: ""
      },
      getConfig: { client: "work", type: 17 }, //企业微信公共参数
      userInfo: "",
      userDataUrl: "plugin.wechat-chat-sidebar.frontend.controller.customer.customer.index",
      strUrl: "plugin.wechat-chat-sidebar.frontend.controller.customer.customer.get-user-info",
      memberId: "",
      record_id: "", //编辑id
      active:0,
      recordFlag: false,
      addressShow: false, //选择地区
      accessoryShow: false,
      addressName: "",
      district: district,
      departmentShow: false, //选择部门
      followUpShow: false, //修改跟进记录
      recordActive: 0,
      clientTitle: "客户行业",
      classifyId: -1, //区别不同的上一级ID
      divisionList: [],
      lookImgItem: "", //图片地址
      classifyArr: [],
      divisionListCopy: [],
      childrenIndex: 0, //识别对应的数组ID
      departmentArr: [],
      divisionIndex: -1, //选择下面的分类
      fileList: [],
      //客户piker选择
      showAccessory: false,
      showSource: false, //客户来源
      showEvolve: false, //客户进展
      sourceIndex: 0,
      industryIndex: 0,
      progressIndex:0,
      clientShow: {
        source_name: "",
        industry_name: "",
        progress_name: "",
        classifyName: "",
        addressName: ""
      },
      progressList: [], //客户进展
      industryList: [], //客户行业
      sourceList: [], //客户来源
      browselists: [],
      search: {
        //客户动态信息列表
        type: 1
      },
      isLoadMore: true,
      page: 1,
      totalPage: 0,
      recordList: [
        //客户动态下面的tab记录
        {
          text: "跟进记录",
          value: 1,
          name:'',
          title:'',
          placeName:'跟进人',
          placeTitle:'跟进记录',
          placeTime:" 年/月/日",
          time:"",
        },
        {
          text: "沟通记录",
          value: 2,
          name:'',
          placeName:'沟通人',
          placeTime:" 年/月/日",
          time:""
        },
        {
          text: "流转记录",
          value: 3,
          name:'',
          placeName:'流转人',
          placeTime:" 年/月/日",
          time:""
        },
        {
          text: "资料维护",
          value: 4,
          name:'',
          placeName:'维护人',
          placeTime:" 年/月/日",
          time:""
        },
        {
          text: "浏览轨迹",
          value: 5,
          name:'',
          placeName:'访问端口',
          placeTime:" 年/月/日",
          time:""
        },
        {
          text: "所有动态",
          value: 6,
          placeTime:" 年/月/日",
          time:""
        }
      ],
      clientForm: {
        //客户详情
        mobile: "",
        name: "",
        source_id: "",
        industry_id: "",
        progress_id: "",
        department_id: "",
        prov: "",
        city: ""
      },
      customerList: [],
      testArr: [],
      recursionArr:[], //回显的数据
      fileName: "",
      //多级菜单
      opportunity_id:"",//商机id
      create_name:"",//创建人名称
      cropId:'',
      //优化标签显示
      labeLMore:true,
      labeLClass:false,
      labelShow:false,
      tainShow:false,
      custTimer:false,
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(2050, 10, 1),
      currentDate: new Date(),

      datas:{},
    };
  },
  provide() {
    return {
      handleChildEvent: this.handleChildEvent
    };
  },
  created() {
    // 需要在 调用getAgentConfig之前设置 appjsApiList,appSignSuccess,appSignError

    if(window.localStorage.getItem("member_id")) { //获取群列表的会员ID
      this.memberId = window.localStorage.getItem("member_id") || '0';
    }
  },
  activated() {
    if (this.fun.getKey("crop_id")) {
      this.cropId = this.fun.getKey("crop_id");
      let corp_id = this.fun.getKey("crop_id");
      window.localStorage.setItem("crop_id", corp_id);
    } else {
      this.cropId = window.localStorage.getItem("crop_id") || '0';
    }
    this.initData();
    this.getAgentConfig();
    this.show_picker('status','off');
  },
  deactivated(){
    if(this.$refs.memberRef){
      this.$refs.memberRef.removeEventListener("scroll", this.MemberScroll);
    }
  },
  mounted() {
  },
  methods: {
    submit_confirm(type){
      if(type == 'status'){
        this.show_business_status = false;
        this.business_status_name=this.temporary;
        this.business_status.forEach(item=>{
          if(item.name == this.temporary){
            this.business_form.status_id = item.id
          }
        })
      }else{
        this.show_business_type = false;
        this.business_type_name=this.temporary;
        this.business_type.forEach(item=>{
          if(item.name == this.temporary){
            this.business_form.type_id = item.id
          }
        })
      }
    },
    handleDragOver(event) {
      // 可以添加一些视觉反馈
    },
    handleChildEvent(flag,data,names) {
      this.datas = data;
      this.names=names;
      this.tainShow = flag;
      // 处理数据
    },
    handleDrop(event) {
      if(this.active==0){
        const files = event.dataTransfer.files;
        this.uploadFiles(files);
      }
    },
    uploadFiles(files) {
      const formData = new FormData();
      for (let i = 0; i < files.length; i++) {
        formData.append('file', files[i]);
        formData.append('need_name',1);
      }
      let uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
      let headers = { "Content-Type": "multipart/form-data" };
      axios.post(uploadUrl, formData, { headers})
      .then(response => {
        let {result,msg,data} = response.data;
        this.$toast(msg);
        if(result){
          this.form.files.push(data.img_url);
          this.fileList.push({ url: data.img_url })
        }
      })
      .catch(error => {
        console.error(error);
      });
    },
    onCopy() {
      this.$toast("复制成功")
    },
    initData() {
      this.isLoading = false;
      this.temporary = '';
      this.isLoadMoreMember = true;
      this.labeLMore = true;
      this.active = 0;
      this.current_type = '';
      this.staff_id = '';
    },
    choose(staff_id){
      this.staff_id = staff_id;
      if(this.current_type == 'assignment'){
        $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.customer-manage.transfer-one-customer',{staff_id},'loading').then(res=>{
          if(res.result){
            this.cetails()
            this.show_member = false;
          }
          this.$toast(res.msg);
        })
      }
      if(this.current_type == 'allot'){
        $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.customer-manage.distribution-one-customer',{staff_id},'loading').then(res=>{
          if(res.result){
            this.cetails()
            this.show_member = false;
          }
          this.$toast(res.msg);

        })
      }

      if(this.current_type == 'share'){
        $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.customer-manage.shared-one-customer',{staff_id},'loading').then(res=>{
          if(res.result){
            this.cetails()
            this.show_member = false;
          }
          this.$toast(res.msg);
        })
      }
    },
    MemberScroll(){
      let scrollTop =this.$refs.memberRef.scrollTop;
      let clientHeight =this.$refs.memberRef.clientHeight;
      let scrollHeight =this.$refs.memberRef.scrollHeight;
      if(scrollTop + clientHeight + 105 > scrollHeight){
        if(this.isLoadMoreMember){
          if(this.member_page>=this.member_total_page){
            return;
          }
          console.log("加载更多",this.member_page,this.member_total_page);

          this.isLoadMoreMember = false;
          let page = this.member_page + 1;

          $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.search-staff",{keywork:this.keywork,page},'loading').then(res=>{
            if(res.result){
              this.isLoadMoreMember = true;
              this.member_list = this.member_list.concat(res.data.staff.data)
              this.member_page = res.data.staff.current_page;
              this.member_total_page = res.data.staff.last_page;
            }
          })
        }
      }
    },
    handle_member(type){

      if(type == 'assignment' || type == 'share' || type == 'allot'){
        this.member_list = [];
        this.current_type = type;
        this.show_member = true;
        this.member_page = 1;
        this.$nextTick(()=>{
          this.$refs.memberRef.addEventListener("scroll", this.MemberScroll);
        })
      }else if(type == 'receive'){
        Dialog.confirm({
          title: '提示',
          message: '是否领取该客户',
        })
          .then(() => {
            $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.customer-manage.receive-one-customer',{},'loading').then(res=>{
              this.$toast(res.msg);
              if(res.result){
                this.cetails();
               }
            })
          })
          .catch(() => {
            // on cancel
          });
      }else{
        Dialog.confirm({
          title: '提示',
          message: '确认放弃该客户吗？',
        })
          .then(() => {
            $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.customer-manage.abandon-one-customer',{staff_id:this.staff_id},'loading').then(res=>{
              this.$toast(res.msg);
              if(res.result){
               this.cetails();
              }
            })
          })
          .catch(() => {
            // on cancel
          });
      }

    },
    into_group_chat(chatId){
      $http
        .get("plugin.wechat-chat-sidebar.frontend.controller.index.get-config", {crop_id:this.cropId,url: this.fun.isIosOrAndroid() === "ios" ? window.initUrl : document.location.href }, "loading")
        .then(response => {
          if (response.result === 1) {
            this.agentData = response.data;
            let get_token = response.data.get_token;
            let config = {
              debug: false,
              beta: true,
              jsApiList: ["agentConfig"],
              openTagList: ["ww-open-data"],
              appId: this.agentData.corpid,
              nonceStr: get_token.noncestr,
              timestamp: get_token.timestamp,
              signature: get_token.token
            };
            wx.config(config);
            wx.ready(() => {
              setTimeout(() => {
                wx.agentConfig({
                  corpid:  config.appId,
                  agentid: this.agentData.agentid,
                  timestamp:config.timestamp,
                  nonceStr:  config.nonceStr,
                  signature:  get_token.app_token,
                  jsApiList: ['openExistedChatWithMsg'], //必填，传入需要使用的接口名称
                  success: ()=> {
                    wx.invoke("openExistedChatWithMsg", {chatId},
                    function(res){
                      console.log(res);
                      if (res.err_msg == "openExistedChatWithMsg:ok"){ }
                    });
                    },
                    fail: function(res) {
                      console.log(res,"fail");
                        if(res.errMsg.indexOf('function not exist') > -1){
                            alert('版本过低请升级')
                        }
                    }
                });
              }, 500);
            });
            wx.error(res => {
              console.log("getAgentConfig：：config信息验证失败！" + JSON.stringify(res));
            });
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(error => {
          console.log("getAgentConfig::", error);
        });
    },
    onCancle(){
      this.keywork = '';
    },
    search_record(){
      let staff_name = this.recordList[this.recordActive-1].name;
      let content = this.recordList[this.recordActive-1].title;
      console.log(this.recordActive,'this.recordActive===');
      if(this.recordActive!==5&&this.recordActive!==6){
        this.search.staff_name = staff_name;
      }
      console.log(content,'content',staff_name,'=====');
      this.search.content = content;
      this.dynamicList();
    },
    custTimerOn() {
      this.search.created_at = Math.floor(new Date(this.currentDate).getTime()/1000);
      var now = new Date(this.currentDate);
      var year = now.getFullYear(); // 年
      var month = now.getMonth() + 1; // 月
      var day = now.getDate()<10?'0'+now.getDate():now.getDate(); // 日
      var today =' '+year + "/" + month + "/" + day;
      this.recordList[this.recordActive-1].time = today;
      if(this.recordActive==6){
        this.dynamicList();
      }
      this.custTimer = false;
    },
    
    onSearch(){
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.search-staff",{keywork:this.keywork,page:1},'loading').then(res=>{
        if(res.result){
          this.isLoadMoreMember = true;
          this.member_list = res.data.staff.data
          this.member_page = res.data.staff.current_page;
          this.member_total_page = res.data.staff.last_page;
        }
      })
    },
    checkImageType(str,type){
      let _type = str.split(".")[1];
      if(type == 'image'){
        if(_type == 'png' || _type == 'jpg' ){
          return true;
        }else{
          return false;
        }
      }else{
        if(_type !== 'png' && _type !== 'jpg' ){
          return true;
        }else{
          return false;
        }
      }

    },
    async show_detais({id}){
      this.files_list = [];
      this.file_ids  = [];
      this.show_details_page = true;
      let {result,msg,data} = await $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.opportunity.details",{opportunity_id:id});
      if(result){
            this.opportunity_id = id;
            this.business_form.name = data.name;
            this.business_form.details = data.details;
            this.business_status_name = data.has_one_status.name;
            this.business_type_name = data.has_one_type.name;
            this.business_form.status_id =data.has_one_status.id
            this.business_form.type_id =data.has_one_type.id
            this.create_name= data.has_one_staff.name; //创建人名称
            this.file_ids = data.file_id.split(",");
            if(data.annex_list && data.annex_list.length!==0){
                data.annex_list.forEach(item=>{
                  this.files_list.push({
                    file_name:item.file_name,
                    file_url:item.file_url,
                    id:item.id,
                    type:item.file_name.substring(item.file_name.lastIndexOf('.')+1)
                  })
                })
            }
            console.log(this.file_ids,"this.file_ids");
        }else{
          this.$toast(msg);
        }
    },

    go_back(){

      this.show_details_page = false;
      for (let item in this.business_form) {
        this.business_form[item] = '';
      }
      this.files_list = [];
      this.business_type_name= '';
      this.business_status_name= '';
      this.file_ids = []
    },
    async submit_handle(){
      let json = {
          form:{
            details:this.business_form.details,
            name:this.business_form.name,
            status_id:this.business_form.status_id,
            type_id:this.business_form.type_id,

          }
      }
        if(this.file_ids && this.file_ids.length!==0){
          let file_id = '';
          file_id =  this.file_ids.join(',')
          json.form.file_id = file_id;
        }
        if(this.opportunity_id){
          json.opportunity_id  = this.opportunity_id;
        }
      let {result,msg} =  await $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.opportunity.save',json);
      this.$toast(msg);
      if(result){
        for (const key in this.business_form) {
          this.business_form[key] = ''
        }
        this.business_status_name = '';
        this.business_type_name = '';
        this.show_details_page = false;
        this.file_ids = [];
        this.getBusinessData({page:1})
      }
    },

    async getBusinessData(json){
      let {result,data,msg} =   await $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.opportunity.index",json);
      this.isLoadMore = true;
      if(result){
       this.page = data.current_page;
       this.totalPage = data.last_page;
       if(data.current_page==1){
        this.business_list = data.data || [];
       }else{
        this.business_list = this.business_list.concat(data.data);
       }
      }else{
       this.$toast(msg);
      }
    },
     search_handle(){
      this.getBusinessData({search:{...this.business_form}})
    },
    onConfirmType(e,value){
      this.temporary = value;
    },
    onChangeStatus(e,value){
      this.temporary = value;
    },
    async show_picker(type,flag='on'){
      this.business_type = [];
      this.business_status = [];
      this.business_columns_status = [];
      this.business_columns_type = [];
      let {msg,data,result} = await $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.opportunity.get-select-condition')
      if(result){
        this.business_type = data.type_list;
        this.business_status = data.status_list;
        data.status_list.forEach(item=>{
          this.business_columns_status.push(item.name)
        })
        data.type_list.forEach(item=>{
          this.business_columns_type.push(item.name)
        })
        // this.business_columns_status = data.status_list;
        // this.business_columns_type = data.type_list;
      }else{
        this.$toast(msg)
      }
      if(flag=='off')return;
      if(type == 'status'){
        this.show_business_status = true;
      }else{
        this.show_business_type = true;
      }
      this.popup_title = type ==  'status'?'商机状态':'商机类型'
      this.temporary = '';
    },
    // 企业微信配置信息
    getAgentConfig() {
      $http
        .get("plugin.wechat-chat-sidebar.frontend.controller.index.get-config", {crop_id:this.cropId,url: this.fun.isIosOrAndroid() === "ios" ? window.initUrl : document.location.href }, "loading")
        .then(response => {
          if (response.result === 1) {
            this.agentData = response.data;
            let get_token = response.data.get_token;
            let config = {
              debug: false,
              beta: true,
              jsApiList: ["agentConfig"],
              openTagList: ["ww-open-data"],
              appId: this.agentData.corpid,
              nonceStr: get_token.noncestr,
              timestamp: get_token.timestamp,
              signature: get_token.token
            };
            wx.config(config);
            wx.ready(() => {
              setTimeout(() => {
                this.getAgentSign(config, get_token.app_token);
              }, 500);
            });
            wx.error(res => {
              console.log("getAgentConfig：：config信息验证失败！" + JSON.stringify(res));
            });
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(error => {
          console.log("getAgentConfig::", error);
        });
    },
    // 企业微信登录
    getAgentSign(config, app_token) {
      wx.agentConfig({
        debug: false,
        corpid: config.appId,
        agentid: this.agentData.agentid,
        timestamp: config.timestamp,
        nonceStr: config.nonceStr,
        signature: app_token,
        jsApiList: ["getCurExternalContact",'getContext','getCurExternalChat'],
        success: () => {
          wx.invoke('getContext', {}, (res)=>{
            if(res.err_msg == "getContext:ok"){
                let entry  = res.entry ; //返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
                console.log("=========获取进入H5页面的入口环境 ====: ",entry);
                if(entry == 'group_chat_tools'){
                  this.getUserData();//获取群绑定的外部联系人的会员ID,若为空则表示没有绑定外部联系人
                } else {
                  wx.invoke("getCurExternalContact", {}, res => {
                    console.log("getCurExternalContact:::", res);
                    if (res.err_msg == "getCurExternalContact:ok") {
                      // console.log("getCurExternalContact:ok ::::::::::::::", res.userId);
                      this.getCustomerInfo(res.userId); //返回当前外部联系人userId
                    } else {
                      //错误处理
                      this.errorLogHandler("getCurExternalContact", res);
                      this.$toast("获取当前外部联系人失败！");
                    }
                  });

                }
              }else {
                //错误处理
                console.log('wx.getContext err::',res);
              }
          });

        },
        fail: res => {
          // this.getCustomerInfo(res.userId); //返回当前外部联系人userId
          this.errorLogHandler("wx.agentConfig", res);
          this.$toast("您没有查看权限，请联系管理员！");
        }
      });
    },
    // 发送外部联系人id
    getCustomerInfo(userId = '') {
      console.log(this.agentData);
      $http
        .get("plugin.wechat-chat-sidebar.frontend.controller.index.get-customer-info", { user_id: userId,crop_id:this.cropId, ...this.getConfig }, "获取联系人...")
        .then(response => {
          if (response.result === 1) {
            this.getUserData();
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(err => {
          console.log("getCustomerInfo::err", err);
        });
    },
    getUserData() {
      $http
        .get(this.userDataUrl, {crop_id:this.cropId,member_id:this.memberId || '',...this.getConfig}, "loading")
        .then(res => {
          if (res.result === 1) {
            if (res.data.member && res.data.member.hasAuth == 0) {
              this.$dialog.alert({ message: "暂无权限" }).then(() => {
                // this.$router.push(this.fun.getUrl("member"));
              });
            }
            let memberInfo = res.data.member;
            this.memberId = memberInfo?.yz_member?.member_id;
            this.getUserMember();
            this.dynamicList();
            this.dynamicSet();
            this.getBusinessData({page:1});
          } else {
            this.$toast(res.msg);
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    getUserMember() {
      $http
        .get(this.strUrl, { ...this.getConfig,crop_id:this.cropId,member_id: this.memberId }, "loading")
        .then(res => {
          if (res.result === 1) {
            this.userInfo = res.data;

          } else {
            this.$toast(res.msg);
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    // 错误日志
    errorLogHandler(logType, err) {
      $http
        .get("plugin.wechat-chat-sidebar.frontend.controller.index.recordErrorLog", { logType, err }, "loading")
        .then()
        .catch(err => {
          console.log(err);
        });
    },
   
    debounce(fn, delay) {
      let last, deferTimer;
      return function(args) {
        let that = this;
        let _args = arguments;
        let now = +new Date();
        if (last && now < last + delay) {
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function() {
            last = now;
            fn.apply(that, _args);
          }, delay);
        } else {
          last = now;
          fn.apply(that, _args);
        }
      };
    },
    getOtherMember(){
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.customer.get-follow-user-list&client=work").then(({result,msg,data})=>{
        if(result!==1){
          return this.$toast(msg);
        }
        this.otherMemberList = data.list;
        console.log(data,"data====");
      })
    },
    activeOn(name) {
      if (name === 0) {
        this.dynamicList();
      }else if(name==2){
        this.getOtherMember();
        $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.customer-group.get-group-list",{},"loading").then(res => {
          if(res.result){
            this.customer_base = res.data.group_list.data;
            this.page =  res.data.group_list.current_page;
            this.totalPage = res.data.group_list.last_page;
          }else{
            this.$toast(res.msg)
          }
        })
      }else if(name==3){
        this.show_details_page = false;
        this.getBusinessData({page:1})
      }else {
        this.dynamicSet();
      }
      this.files_list = [];
      this.file_ids=[];//客户商机文件
      this.business_type_name = '';
      this.business_status_name = '';
      this.opportunity_id = '';
      this.create_name = '';
      this.business_form = {
        status_id:"",
        type_id:"",
        staff:"",
        name:"",
        details:""
      };
    },
    accessoryClick() {
      this.accessoryShow = false;
    },
    cancelClick(show) {
      //客户管理piker弹窗
      this.showSource = false;
      this.showAccessory = false;
      this.showEvolve = false;
    },
    fileDelete(data, file) {
      let filesArr = this.form.files;
      this.form.files = filesArr.splice(file.index, 1);
    },

    pickerConfirm(obj) {
      //客户进展弹窗提交
      this.clientForm[obj.typeName] = obj.id;
      this.clientShow[obj.valuekey] = obj.title;
      this.showSource = false;
      this.showAccessory = false;
      this.showEvolve = false;
    },
    lookImg(url) {
      this.lookImgItem = url;
      this.accessoryShow = true;
    },
    cancelFollow(show) {
      //关闭弹窗
      this.followUpShow = show;
      this.form.content = "";
      this.record_id = "";
    },
    updateConfirm(obj) {
      this.form.content = obj.data;
      if (this.form.content === "") {
        this.$toast.fail("请先填写跟进记录内容");
        return;
      }
      this.followUpShow = obj.show;
      this.clientAdd();
    },
    onClientChange(value, title) {
      //tab标签切换
      this.search.type = value;
      this.page = 1;
      this.recordList[value-1].name = '';
      this.recordList[value-1].title = '';
      this.recordList[value-1].time = '';
      if (this.search.type === 5) {
        this.browselist();
        this.customerList = [];
      } else {
        if(this.recordActive==1){
          this.search.content = ''
        }
        if(value==6){
          this.search.type = '';
        }
        this.search.staff_name = '';
        this.search.created_at = '';
        this.dynamicList();
      }
    },
    updateRecord(data) {
      //修改跟进记录
      let {id,content} = data;
      this.record_id = id;
      this.form.content = content;
      this.followUpShow = true;
    },
    clientDelete(id, files, index,type='') {
      if(type == 'business'){ //商机附件
        this.$dialog
        .confirm({
          message: "是否删除文件"
        })
        .then(() => {
          let _fileArr = this.files_list;
          let _file_ids = this.file_ids;
          _fileArr.splice(index,1);
          _file_ids.splice(index,1);
          this.files_list = _fileArr;
          this.file_ids = _file_ids;
        })
        .catch(() => {
          // on cancel
        });

        return;
      }
      //删除跟进文件
      // this.$dialog
      //   .confirm({
      //     message: "是否删除文件"
      //   })
      //   .then(() => {
      //     let fileArr = [];
      //     fileArr = files.splice(index, 1);
      //     this.form.files[0] = fileArr[0].url;
      //     this.record_id = id;
      //     this.followupApi();
      //   })
      //   .catch(() => {
      //     // on cancel
      //   });
    },
     //删除跟进文件
     clientUpdate(data){
      let {url,id} = data;
      this.form.files = url;
      this.record_id = id;
      this.followupApi();
     },
    clientDel(data){
      let {url,id} = data;
      if(url){
        this.form.files = url;
      }else{
        this.form.files =  [];

      }
      this.record_id = id;
      this.followupApi();
    },
    clientDownload(files, index,type='') {
      if(type == 'business'){
        uploadUrl = this.fun.getRealUrl("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.downloadFile", {});
        this.fileName = files.file_name;
        let options = { url: files.file_url };
        this.exportDownload(uploadUrl, options,this.fileName);
        return;
      }
    },
    clientDown(data) {
      let {uploadUrl,options,fileName} = data;
      this.exportDownload(uploadUrl, options,fileName);
    },
    exportDownload(url, options = {},fileName) {
      return new Promise((resolve, reject) => {
        this.isLoading = true;
        axios.defaults.headers["content-type"] = "application/json;charset=UTF-8";
        axios({
          method: "post",
          url: url, // 请求地址
          data: options, // 参数
          responseType: "blob" // 表明返回服务器返回的数据类型
        }).then(
          response => {
            this.isLoading = false;
            resolve(response.data);
            let blob = new Blob([response.data]);
            // let fileName = Date.parse(new Date()) + this.fileName;
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName);
            } else {
              var link = document.createElement("a");
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          },
          err => {
            this.isLoading = false;
            reject(err);
          }
        );
      });
    },
    saveCustomer() {
      if (this.clientForm.name === "") {
        this.$toast.fail("请先填写客户名称");
        return;
      }
      if (this.clientForm.mobile === "") {
        this.$toast.fail("请先填写客户电话");
        return;
      }
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.save-customer", { form: this.clientForm }, "正在获取").then(
        response => {
          if (response.result == 1) {
            this.$toast("提交成功");
            this.dynamicSet();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    dynamicSet() {
      //获取客户资料
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-set", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.progressList = res.progress_list; //客户进展
            this.industryList = res.industry_list;
            this.sourceList = res.source_list;
            this.divisionList = Array.from(res.department_list);
            this.divisionListCopy = Array.from(res.department_list);

            this.cetails(); //再获取客户信息
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          this.$dialog.alert({ message: response.msg });
          // console.log(response);
          // error callback
        }
      );
    },
    cetails() {
      //客户基本信息
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-customer-details", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.has_owned = res.has_owned;
            this.recover_day = res.recover_day;
            this.member_name = res.manage_staff.name || '无';
            this.clientForm.name = res.name;
            this.clientForm.mobile = res.mobile;
            this.clientForm.source_id = res.source_id || "";
            this.clientForm.industry_id = res.industry_id || "";
            this.clientForm.progress_id = res.progress_id || "";
            this.clientForm.city = res.city || "";
            this.clientForm.prov = res.prov || "";
            this.clientShow.addressName = res.city?.areaname;
            let department = res.has_one_department;
            if (res.has_one_department) {
              this.clientForm.department_id = department.id;
              this.classifyId = department.id;
              this.Circulararray(this.classifyId, this.divisionList);
              console.log(this.testArr);
              this.classifyId = this.testArr.parent_id;
              this.departmentArr = this.findIndexArray(this.divisionList, department.id, []); //反查上一级的数组显示

              this.clientShow.classifyName = department.name;
              this.divisionList = this.testArr.children || [];
            }

            this.progressList.forEach((item, index) => {
              if (item.id === this.clientForm.progress_id) {
                this.clientShow.progress_name = item.progress_name;
                this.progressIndex = index;
              }
            });
            this.industryList.forEach((item, index) => {
              if (item.id === this.clientForm.industry_id) {
                this.clientShow.industry_name = item.industry_name;
                this.industryIndex = index;
              }
            });
            this.sourceList.forEach((item, index) => {
              if (item.id === this.clientForm.source_id) {
                this.clientShow.source_name = item.source_name;
                this.sourceIndex = index;
              }
            });
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    findIndexArray(data, id, indexArray) {
      //设置数组arr 存放父级id
      let arr = Array.from(indexArray);
      //遍历data数据
      for (let i = 0, len = data.length; i < len; i++) {
        //把当前层的pid 存到数字中
        // arr.push(data[i].parent_id);
        arr.push({
          id: data[i].id,
          parent_id: data[i].parent_id,
          text: data[i].text,
          children: data[i].children || []
        });
        if (data[i].id === id) {
          // 循环结束，返回所有id的数组集合
          return arr;
        }
        let children = data[i].children;
        //继续循环
        if (children && children.length) {
          let result = this.findIndexArray(children, id, arr);
          if (result) return result;
        }
        // 当前层的pid 不是指定的父级pid 移除掉
        arr.pop();
      }
      return false;
    },
    clientAdd() {
      //发表跟进记录
      if (this.form.content === "") {
        this.$toast.fail("请先填写跟进记录内容");
        return;
      }
      this.followupApi();
    },
    followupApi() {
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.save-followup", { form: this.form, record_id: this.record_id }, "正在获取").then(
        response => {
          if (response.result == 1) {
            this.$toast(response.msg);
            this.form.content = "";
            this.form.files = [];
            this.fileList = [];
            this.dynamicList();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    dynamicList() {
      //客户动态信息列表
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-customer-dynamic-list", { search: this.search }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let data = res.data;
            this.isLoadMore = true;
            this.totalPage = res.last_page;
            if (!this.totalPage) {
              this.page = 0;
            }
        
            this.customerList = data || [];
            if(data.length <= 0) return;
            for (const key in this.customerList) {
              if(this.customerList[key]&&this.customerList[key].length!==0){
                console.log(this.customerList[key],'this.customerList[key]====');
                this.customerList[key] = this.customerList[key].map(item=>{
                  return {...item,edit_btn:false,show_more:false}
                })
              }
        
            }
            
      
            console.log(this.customerList, 'customerListcustomerList');
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {  
          // console.log(response);
          // error callback
        }
      );
    },
    browselist() {
      //浏览轨迹
      $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-customer-browse-list", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.isLoadMore = true;
            this.totalPage = res.last_page;
            if (!this.totalPage) {
              this.page = 0;
            }
            this.browselists = res.data;
          } else {
            this.page = this.page - 1;
            this.isLoadMore = false;
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.totalPage) {
        return;
      } else {
        if(this.active ==2){
          let page = this.page + 1;
          $http.post("plugin.wechat-chat-sidebar.frontend.controller.customer.customer-group.get-group-list",{page}).then(res=>{
            if(res.result){
              this.customer_base = this.customer_base.concat(res.data.group_list.data);
              this.page =  res.data.group_list.current_page;
              this.totalPage = res.data.group_list.last_page;
            }else{
              this.$toast(res.msg)
            }
          })
          return;

        }
        if(this.active == 3){
          let page = this.page + 1;
          this.getBusinessData({page,...this.business_form})
          return;
        }
        this.page += +1;
        let api = "";
        let query = "";
        if (this.search.type === 5) {
          query = {
            page: this.page
          };
          api = "plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-customer-browse-list";
        } else {
          query = {
            search: this.search,
            page: this.page
          };
          api = "plugin.wechat-chat-sidebar.frontend.controller.customer.dynamic.get-customer-dynamic-list";
        }
        $http.post(api, query, "正在获取").then(
          response => {
            if (response.result == 1) {
              let res = response.data;
              let list = res.data;
              this.isLoadMore = true;
              if (this.search.type === 5) {
                this.browselists = [...this.browselists, ...list];
              } else {
                if(list.length <= 0) return;
                this.customerList = { ...this.customerList, ...list };
                for (const key in this.customerList) {
                  this.customerList[key] = this.customerList[key].map(item=>{
                    return {...item,edit_btn:false,show_more:false}
                  })
                }
              }
            } else {
              this.page = this.page - 1;
              this.isLoadMore = false;
              this.$dialog.alert({ message: response.msg });
            }
          },
          function(response) {
            // console.log(response);
            // error callback
          }
        );
      }
    },
    callPhone(phoneNumber) {
      window.location.href = "tel://" + phoneNumber;
    },
    accessoryConfirm(event) {
      this.showAccessory = false;
    },
    accessoryCancel() {
      this.showAccessory = false;
    },
    divisionCancel() {
      //部门的弹窗
      this.departmentShow = false;
    },
    divisionAffirm() {
      //提交部门ID
      if (this.departmentArr.length > 0) {
        if (this.clientForm.name === "") {
          this.$toast.fail("请先填写客户名称");
          return;
        }
        if (this.clientForm.mobile === "") {
          this.$toast.fail("请先填写客户电话");
          return;
        }
        let id = this.departmentArr[this.departmentArr.length - 1].id;
        let text = this.departmentArr[this.departmentArr.length - 1].text;
        this.clientForm.department_id = id;
        this.clientShow.classifyName = text;
        this.departmentShow = false;
      } else {
        this.$toast("请选择部门分类");
      }
    },
    departmentOn(data, index) {
      console.log(this.classifyId);
      let classifyObj = {};
      this.divisionList = data.children || [];
      if (this.classifyId === data.parent_id) {
        classifyObj = {
          id: data.id,
          parent_id: data.parent_id,
          text: data.text,
          children: data.children || []
        };
        this.departmentArr[this.childrenIndex] = classifyObj;
      } else {
        this.departmentArr.push({
          id: data.id,
          parent_id: data.parent_id,
          text: data.text,
          children: data.children || []
        });
      }

      this.divisionIndex = index;
    },
    departmentPopup() {
      this.departmentShow = true;
      // this.classifyId = 0;
      // this.departmentArr = [];
    },
    departmentArrOn(index, data) { //重新选择不同的菜单子级
      this.divisionIndex = -1;
      this.childrenIndex = index;
      this.classifyId = data.parent_id;
      this.divisionList = data.children || [];
      this.departmentArr = this.departmentArr.splice(0, index + 1);
      if (data.parent_id === 0) {
        this.divisionList = this.divisionListCopy;
      } else {
        this.Circulararray(data.parent_id, this.divisionListCopy);
        this.divisionList = this.testArr?.children;
      }
    },
    Circulararray(v, list) {
      //递归遍历数组
      // debugger;
      if (!list) return;
      let data = null;

      list.map((item, index) => {
        if (item.id !== v) {
          return this.Circulararray(v, item.children);
        } else {
          data = item;
          this.testArr = data;
          return;
          // return data;
        }
      });
    },
    addressCallback(obj) {
      let provObj = {
        id: obj.itemValue1,
        areaname: obj.itemName1,
        parentid: 0,
        level: 1
      };
      let cityObj = {
        id: obj.itemValue2,
        areaname: obj.itemName2,
        parentid: obj.itemValue1,
        level: 2
      };
      this.clientForm.prov = provObj;
      this.clientForm.city = cityObj;
      this.clientShow.addressName = obj.itemName2;

      this.addressShow = false;
    },
    multipleMethod(e, flag) {
      if (e && e.length) {
        for (let i = 0; i < e.length; i++) {
          this.onRead(e[i], flag);
        }
      } else this.onRead(e, flag);
    },
    add_business(){
      this.files_list = [];
      this.business_status_name = '';
      this.business_type_name = '';
      for (let item in this.business_form) {
        this.business_form[item] = '';
      }
      this.show_details_page = true;

    },
    onRead(e, flag) {
      e.status = "uploading";
      e.message = "上传中...";
      let fd = new FormData();
      fd.append("file", flag === true ? e : e.file);
      fd.append('need_name',1)
      // if (flag === true) {
      //   fd.append("file", e); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      // } else {
      //   fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      // }
      console.log(fd,"fd=====");
      let uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
      let headers = { "Content-Type": "multipart/form-data" };

      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "正在上传中...",
        selector: "#custom-selector"
      });
      if(this.active==3){
        uploadUrl = this.fun.getRealUrl("plugin.wechat-chat-sidebar.frontend.controller.customer.opportunity.upload", {});
        uploadUrl = uploadUrl + '&type=17&client=work';
        fd.append('upload_type',e.file.type.split("/")[0]);
        console.log(fd,"fd");
        axios.post(uploadUrl, fd, { headers }).then(({ data: { result, msg, data } }) => {
            this.$toast.clear();
            if (result === 1) {
              // e.status = "done ";
              this.file_ids.push(data.id);
              this.files_list.push({
                file_name:data.file_name,
                id:data.id,
                file_url:data.file_url,
                type:data.file.slice(data.file.lastIndexOf('.')+1)
              })
            } else {
              // this.files_list.push( {
              //   file_name: "WechatIMG3134.jpg",
              //   type:"jpg",
              //   "file_size": 409,
              //   file_url:"https://ysm-1251768088.cos.ap-guangzhou.myqcloud.com/images/25/2025/02/e6e4e5594e670328f4fbb5b0559448a3.jpg",
              //   id:this.files_list.length+1,
              // })

              this.$toast(msg);
              // e.status = "failed";
              // e.message = "上传失败";
            }
        }).catch(error => {
          this.$toast.clear();
          console.log(error);
        });
        return;
      }
      axios
        .post(uploadUrl, fd, { headers })
        .then(({ data: { result, msg, data } }) => {
          this.$toast.clear();
          if (result === 1) {
            e.status = "done ";
            this.form.files.push(data.img_url);
          } else {
            this.$toast(responseData.msg);
            e.status = "failed";
            e.message = "上传失败";
          }
        })
        .catch(error => {
          this.$toast.clear();
          console.log(error);
        });
    }
  },
  components: {
    clientPicker,
    browseList,
    followPopup,
    customerLabel,
    recordData,
    maintainPopup,
    loadingC
  }
};
